// import 'package:flutter/material.dart';
// import 'package:webview_flutter/webview_flutter.dart';
// import 'pet.dart';
//
// class PetsDetailPage extends StatefulWidget {
//   final Pet pet;
//
//   const PetsDetailPage({super.key, required this.pet});
//
//   @override
//   _PetsDetailPageState createState() => _PetsDetailPageState();
// }
//
// class _PetsDetailPageState extends State<PetsDetailPage> {
//   WebViewController? controller;
//   bool loaded = false;
//
//   @override
//   void initState() {
//     super.initState();
//     controller = WebViewController()
//       ..setJavaScriptMode(JavaScriptMode.unrestricted)
//       ..setNavigationDelegate(
//         NavigationDelegate(
//           onPageFinished: (url) {
//             setState(() {
//               loaded = true;
//             });
//           },
//         ),
//       )
//       ..loadRequest(Uri.parse(widget.pet.url));
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text(
//           widget.pet.name,
//           overflow: TextOverflow.ellipsis,
//           style: const TextStyle(fontSize: 16.0),
//         ),
//         backgroundColor: Colors.blue,
//       ),
//       body: Stack(
//         children: [
//           if (controller != null)
//             WebViewWidget(controller: controller!),
//           if (!loaded)
//             const Center(child: CircularProgressIndicator()),
//         ],
//       ),
//     );
//   }
// }


import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'ChatDetailPage.dart';
import 'Pet.dart';

class PetsDetailPage extends StatefulWidget {
  final Pet pet;
  final List<Map<String, String>> friends; // 传入的好友列表

  const PetsDetailPage({super.key, required this.pet, required this.friends});

  @override
  _PetsDetailPageState createState() => _PetsDetailPageState();
}

class _PetsDetailPageState extends State<PetsDetailPage> {
  WebViewController? controller;
  bool loaded = false;
  bool isFavorite = false;

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (url) {
            setState(() {
              loaded = true;
            });
          },
          onWebResourceError: (error) {
            setState(() {
              loaded = false;
            });
            _showErrorDialog();
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.pet.url));
  }

  // 错误提示对话框
  void _showErrorDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('加载失败'),
          content: const Text('无法加载宠物详情页面，请检查网络连接。'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  // 切换收藏状态
  void _toggleFavorite() {
    setState(() {
      isFavorite = !isFavorite;
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(isFavorite ? '已收藏' : '已取消收藏'),
        duration: const Duration(seconds: 1),
      ),
    );
  }

  // 分享功能：弹出好友列表以选择好友
  void _sharePetInfo() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('选择好友'),
          content: SizedBox(
            height: 400,
            width: 300,
            child: ListView.builder(
              itemCount: widget.friends.length,  // 使用传入的 friends 数据
              itemBuilder: (context, index) {
                var friend = widget.friends[index];
                return ListTile(
                  leading: CircleAvatar(
                    backgroundImage: AssetImage(friend['avatar']!),
                  ),
                  title: Text(friend['name']!),
                  onTap: () {
                    // 选择好友后，关闭弹框并进入聊天界面，传递宠物信息
                    Navigator.of(context).pop();
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => ChatDetailPage(
                          friendName: friend['name']!,
                          friendAvatar: friend['avatar']!,
                          initialMessages: friend['messages']?.split(',') ?? [],
                          lastMessageNotifier: ValueNotifier({}),
                          friendIndex: index,
                          updateMessagesCallback: (messages) {},
                          petInfo: {
                            'name': widget.pet.name,
                            'url': widget.pet.url,
                          },
                        ),
                      ),
                    );
                  },
                );
              },
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.pet.name,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(fontSize: 16.0),
        ),
        backgroundColor: Colors.blue,
        actions: [
          IconButton(
            icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),
            onPressed: _toggleFavorite,
          ),
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: _sharePetInfo,
          ),
          IconButton(
            icon: const Icon(Icons.home),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
      body: Stack(
        children: [
          if (controller != null)
            WebViewWidget(controller: controller!),
          if (!loaded)
            const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }
}


